/*
 * $Id$
 */
package py.firefly.web.dict;


import java.io.BufferedInputStream;

import java.sql.Blob;
import java.sql.ResultSet;

import java.util.zip.GZIPInputStream;

import javax.sql.DataSource;

import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;

import py.firefly.util.DataSources;

/**
 * Reads entry definition from the database.
 *
 * @author myang
 */
public class EntryDbReader implements EntryReader {

    private final static DataSource DS = DataSources.getDataSource();

    private JdbcTemplate _jdbcTemplate;

    public EntryDbReader() {
        _jdbcTemplate = new JdbcTemplate(DS);
    }

    @Override
    public String read(final String entry) {
        final String sql = "select * from dict_definitions where entry = ?";
        return _jdbcTemplate.queryForObject(sql, new RowMapper<String>() {
            @Override
            public String mapRow(final ResultSet rs, int i) {
                try {
                    final Blob b = rs.getBlob("definition");
                    final BufferedInputStream bis =
                      new BufferedInputStream(new GZIPInputStream(b.getBinaryStream()));
                    final byte[] bb = new byte[rs.getInt("size")];
                    try {
                        bis.read(bb);
                        return new String(bb, "UTF-8");
                    }
                    finally {
                        if (null != bis) {
                            bis.close();
                        }
                    }
                } catch (final Exception ex) {
                    return ex.getMessage();
                }
            }
        }, entry);
    }
}
